package com.bgi.uims.pub.web;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpSession;
import javax.servlet.http.HttpSessionEvent;
import javax.servlet.http.HttpSessionListener;

import com.bgi.uims.pub.utils.ConfigConst;
import com.bgi.uims.pub.utils.Constant;
/**
 * 
*    
* @项目名称：
* @类名称：OnlineUserListener
* @类描述：在线用户监控，用于session自动注销时存储退出时间
* @创建人：fukun
* @创建时间：2013-8-18 上午11:01:07
* @version： 1.0
*
 */

public class OnlineUserListener implements HttpSessionListener {

	public void sessionCreated(HttpSessionEvent event) {
		
	}
	
	@SuppressWarnings({ "rawtypes" })
	public void sessionDestroyed(HttpSessionEvent event) {
		HttpSession session = event.getSession();
		ServletContext application = session.getServletContext();
		List sessions = (ArrayList) application.getAttribute(Constant.SESSIONS);
		//记录离开时间
		if(session.getAttribute(Constant.LOGINLOG_ID)!=null)
		{
			//存储退出时间
			updateLog(session.getAttribute(Constant.LOGINLOG_ID).toString());
			session.removeAttribute(Constant.LOGINLOG_ID);
		}
		session.removeAttribute(Constant.DISABLEDRESOURCENAME);
		session.removeAttribute(Constant.DISABLEDRESOURCEURL);
		session.removeAttribute(Constant.LOGINUSER);
		if(sessions!=null)
		{
			sessions.remove(session);
		}
	}
	
	public void updateLog(String id) {
		// 离开时间写入数据库日志
		
		
		if (id != null && !"".equals(id)) {
			String sql = " UPDATE sys_login_log SET logout_time=sysdate,online_time=(TO_NUMBER(sysdate-login_time)*24*60*60) WHERE log_id=?";
			String driverName = ConfigConst.getJDBC_DRIVERCLASSNAME(); // 加载JDBC驱动
			String dbURL = ConfigConst.getJDBC_URL(); // 连接服务器和数据库test
			String userName = ConfigConst.getJDBC_USERNAME(); // 默认用户名
			String userPwd = ConfigConst.getJDBC_PASSWORD(); // 密码
			Connection conn = null;
			PreparedStatement pst = null;
			ResultSet rs = null;
			try {
				Class.forName(driverName);
				conn = DriverManager.getConnection(dbURL, userName, userPwd);
				conn.setAutoCommit(true);
				pst = conn.prepareStatement(sql);
				pst.setString(1, id);
				pst.executeUpdate();
			} catch (Exception e) {
				e.printStackTrace();
			} finally {
				closeAll(conn, pst, rs);
			}
		}
	}
	/**
	 * 执行清理过程
	 * <li>关闭数据库连接</li>
	 * <li>关闭语句对象</li>
	 * <li>关闭结果集</li>
	 * 
	 * @param con
	 * @param s
	 * @param rs
	 */
	public static void closeAll(Connection con, PreparedStatement s, ResultSet rs) {
		try {
			if (null != rs) {
				rs.close();
				rs = null;
			}
			if (null != s) {
				s.close();
				s = null;
			}
			if (null != con) {
				con.close();
				con = null;
			}
		} catch (SQLException sqle) {
			// nothing to do, forget it;
		}
	}

}
